package net.lcqf.http.interceptor;

import com.alibaba.fastjson.JSONObject;
import net.lcqf.http.response.CommonResult;
import net.lcqf.http.token.TokenComponent;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 注册拦截器
 * +----------------------------------------------------------------------
 * | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2018-2024 聊来All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * +----------------------------------------------------------------------
 * | @Author: 贯彻己道的云 <18970881148@qq.com>
 * +----------------------------------------------------------------------
 * | DateTime: 2025/2/10 14:27
 * +----------------------------------------------------------------------
 */

@Service
public class TokenInterceptor implements HandlerInterceptor {

    private final TokenComponent tokenComponent;

    public TokenInterceptor(TokenComponent tokenComponent) {
        this.tokenComponent = tokenComponent;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取 header 的 token 请求参数值
        String token = tokenComponent.getToken(request);
//        if (token == null || token.isEmpty()) { return true; }

        boolean result = tokenComponent.check(token);
        if (!result) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().write(JSONObject.toJSONString(CommonResult.unauthorized()));
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}